<template>
  <a-card :bordered="false">
    <a-form :form="form" style="max-width: 500px; margin: 50px auto 30px;">
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="旧密码">
        <a-input type="password" placeholder="请输入旧密码" v-decorator="['oldpassword', validatorRules.oldpassword]" />
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="新密码">
        <a-input type="password" placeholder="请输入新密码" v-decorator="['password', validatorRules.password]" />
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="确认新密码">
        <a-input
          type="password"
          @blur="handleConfirmBlur"
          placeholder="请确认新密码"
          v-decorator="['confirmpassword', validatorRules.confirmpassword]"
        />
      </a-form-item>

      <a-form-item :wrapperCol="{ span: 24, offset: 5 }">
        <a-button type="primary" @click="onSubmit">修改</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import { updatePassword } from '@/api/api'
import { Modal } from 'ant-design-vue'

export default {
  name: 'UserPassword',
  data() {
    return {
      title: '修改密码',
      //校验规则
      validatorRules: {
        oldpassword: {
          rules: [
            {
              required: true,
              message: '请输入旧密码!'
            }
          ],
          validateTrigger: ['change', 'blur']
        },
        password: {
          rules: [
            {
              required: true,
              message: '请输入新密码!'
            },
            {
              validator: this.validateToNextPassword
            }
          ],
          validateTrigger: ['change', 'blur']
        },
        confirmpassword: {
          rules: [
            {
              required: true,
              message: '请确认新密码!'
            },
            {
              validator: this.compareToFirstPassword
            }
          ],
          validateTrigger: ['change', 'blur']
        }
      },
      confirmDirty: false,

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },

      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      form: this.$form.createForm(this),
      username: ''
    }
  },
  methods: {
    /**
     * 提交表单
     */
    onSubmit() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          var params = {
            old_password: values.oldpassword,
            confirm_password: values.confirmpassword,
            new_password: values.password
          }
          console.log(params)
          updatePassword(params).then(res => {
            if (res.code == 0) {
              that.updatePwdSucc()

              //主动提示登录失效
              setTimeout(() => {
                that.$store.commit('SET_TOKEN', '')
                that.$store.dispatch('LocalLogout').then(() => {
                  window.location.reload()
                })
              }, 1500)
            } else {
              that.updatePwdFailed()
            }
          })
        }
      })
    },

    /**
     * 修改密码成功
     */
    updatePwdSucc() {
      this.$notification['success']({
        message: '操作成功',
        description: '密码修改成功',
        duration: 4
      })
    },

    /**
     * 修改密码失败
     */
    updatePwdFailed(msg) {
      this.$notification['error']({
        message: '操作失败',
        description: msg,
        duration: 4
      })
    },

    /**
     * 新密码校验
     */
    validateToNextPassword(rule, value, callback) {
      const form = this.form
      if (!value) {
        callback()
        return
      }

      let reg = /^(?=.*[a-zA-Z])(?=.*\d).{8,12}$/
      if (!reg.test(value)) {
        // 和特殊符号 大小写
        callback(new Error('密码由8-12位数字、字母组成!'))
        return
      }

      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },

    /**
     * 确认密码校验
     */
    compareToFirstPassword(rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },

    /**
     * 确认密码失去焦点事件
     */
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    }
  }
}
</script>

<style scoped></style>
